package com.example.saveword.save_word;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.example.saveword.R;
import com.example.saveword.dao.UserDao;
import com.example.saveword.dao.WordDao;
import com.example.saveword.dao.StudyRecordDao;
import com.example.saveword.dao.WordRecordDao;
import com.example.saveword.model.StudyRecord;
import com.example.saveword.model.User;
import com.example.saveword.model.Word;
import com.example.saveword.model.WordRecord;
import com.example.saveword.utils.AudioMediaPlayer;
import com.example.saveword.utils.JsonUtils;
import com.example.saveword.utils.LocalTrueFalseMediaPlayer;
import com.example.saveword.utils.SPUtils;
import com.example.saveword.utils.Sentence_split;
import com.example.saveword.utils.SetUserUtils;
import com.example.saveword.utils.TimeUtils;
import com.example.saveword.utils.Tran_CN_split;
import com.example.saveword.utils.mTimeUpdateReceiver;
import com.like.LikeButton;
import com.like.OnLikeListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class MainReviewActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    private User user;
    private TextView word_text, ukphone_text, usphone_text, sentence_text, tranEN_text;//用来显示单词和音标的
    private RadioGroup radioGroup;      //用于加载单词的四个选项
    private LikeButton likeButton;      //收藏按钮
    private RadioButton radioOne, radioTwo, radioThree, radioFour;   //  单词意思的四个选项
    private RadioButton[] radioButtonsgroups = new RadioButton[4];
    private ImageView play_uk_voiceButton, play_us_voiceButton;//播放声音按钮
    private AudioMediaPlayer audioMediaPlayer;//播放音频类
    private LocalTrueFalseMediaPlayer localTrueFalseMediaPlayer;//提示音类
    //数据库操作类
    private WordDao wordDao;
    private WordRecordDao wordRecordDao;
    private StudyRecordDao studyRecordDao;
    int start;    //定位要开始背单词的位置
    int now_pos; // 现在背的单词是在整个needstudy的下标
    private List<Word> needstudy;//需要学习的所有单词
    private Map<Word,Integer> CurCount;//记录今天单词正确次数
    private Word nowword;   //现在正在背的单词
    private mTimeUpdateReceiver timeChangedReceiver; //广播监听系统时间
    private int cnt = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_word_review);
        init();
    }
    public void init() {
        //初始化按钮
        user = (User) JsonUtils.jsonToObject((String) SPUtils.get(this, "User", ""), User.class);
        word_text = findViewById(R.id.word_text);
        ukphone_text = findViewById(R.id.ukphone_text);
        usphone_text = findViewById(R.id.usphone_text);
        sentence_text = findViewById(R.id.sentence_text);
        tranEN_text = findViewById(R.id.tranEN_text);
        radioGroup = findViewById(R.id.choose_group);
        radioOne = findViewById(R.id.choose_btn_one);
        radioTwo = findViewById(R.id.choose_btn_two);
        radioThree = findViewById(R.id.choose_btn_three);
        radioFour = findViewById(R.id.choose_btn_four);

        likeButton=findViewById(R.id.flag_button);

        radioButtonsgroups[0] = radioOne;
        radioButtonsgroups[1] = radioTwo;
        radioButtonsgroups[2] = radioThree;
        radioButtonsgroups[3] = radioFour;

        //初始化播放声音
        play_uk_voiceButton = findViewById(R.id.play_vioce_uk);
        play_us_voiceButton = findViewById(R.id.play_vioce_us);
        audioMediaPlayer = new AudioMediaPlayer(this);
        localTrueFalseMediaPlayer=new LocalTrueFalseMediaPlayer(this);

        //初始化数据库操作
        wordDao = new WordDao(this);
        wordRecordDao = new WordRecordDao(this);
        studyRecordDao = new StudyRecordDao(this);

        //给按钮添加监听
        radioGroup.setOnCheckedChangeListener(this);
        play_uk_voiceButton.setOnClickListener(this);
        play_us_voiceButton.setOnClickListener(this);
        sentence_text.setOnClickListener(this);
        tranEN_text.setOnClickListener(this);
        timeChangedReceiver = new mTimeUpdateReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        registerReceiver(timeChangedReceiver, filter);
        start = studyRecordDao.getStudyCount(user.getWordType());
        needstudy = new ArrayList<>();
        //装填现在需要复习
        needstudy = wordRecordDao.findNeedReview();
        CurCount = new HashMap<>();
        for(Word word : needstudy)
        {
            CurCount.put(word, 0);
            wordRecordDao.AddOrGet(word);
        }
        nowword = needstudy.get(0);
        setword(nowword);
        //给收藏按钮添加监听器
        likeButton.setOnLikeListener(new OnLikeListener(){
            @Override
            public void liked(LikeButton likeButton) {
                wordRecordDao.setFlag(nowword);
                likeButton.setLiked(wordRecordDao.isFlag(nowword));
            }

            @Override
            public void unLiked(LikeButton likeButton) {
                wordRecordDao.setFlag(nowword);
                likeButton.setLiked(wordRecordDao.isFlag(nowword));
            }
        });
    }
    // 根据state更新单词的状态
    void update(int state, Word word)
    {
        if(state == 1)
        {
            int cnt = CurCount.get(word);
            CurCount.remove(word);
            cnt += 1;
            if(cnt == 1)
            {
                //学习记录更新
                cnt++;
                updateStudyRecord();
                updateWordRecord(word);
            }
        }
        else
        {
            CurCount.remove(word);
            WordRecord wordRecord = wordRecordDao.getRecord(word);
            wordRecord.setLevel(1);
            wordRecord.setTimeReview(TimeUtils.getNextReviewTime(wordRecord.getLevel()));
            wordRecordDao.update(wordRecord);
        }
    }
    // 更新今日已经学习的单词数量
    void updateStudyRecord()
    {
        StudyRecord studyRecord = studyRecordDao.addOrGet();
        studyRecord.setRepeatNum(studyRecord.getRepeatNum() + 1);
        studyRecordDao.update(studyRecord);
    }
    void updateWordRecord(Word word) {
        WordRecord wordRecord = wordRecordDao.getRecord(word);
        wordRecord.setLevel(wordRecord.getLevel() + 1);
        wordRecord.setTimeReview(TimeUtils.getNextReviewTime(wordRecord.getLevel()));
        wordRecordDao.update(wordRecord);
    }
    //改变颜色
    private void btnGetText(String msg, RadioButton btn) {

        if (msg.equals(Tran_CN_split.getspit(nowword.getTranCN()))) {
            btn.setBackgroundColor(getResources().getColor(R.color.TIANYUANLV));        //设置选项为绿色
            localTrueFalseMediaPlayer.play(true);//提示音播放
            update(1, nowword);
        } else {
            btn.setBackgroundColor(getResources().getColor(R.color.YANHONG));            //设置选项为红色
            localTrueFalseMediaPlayer.play(false);
            for (int k = 0; k < 4; k++) {                   //设置正确答案的颜色为绿色
                if (radioButtonsgroups[k].getText().toString().substring(3).equals(Tran_CN_split.getspit(nowword.getTranCN()))) {
                    radioButtonsgroups[k].setBackgroundColor(getResources().getColor(R.color.TIANYUANLV));
                    radioButtonsgroups[k].getBackground().setAlpha(191);
                }
            }
            update(0, nowword);
        }

        radioOne.setChecked(false);        //默认不被点击
        radioTwo.setChecked(false);        //默认不被点击
        radioThree.setChecked(false);        //默认不被点击
        radioFour.setChecked(false);        //默认不被点击
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getNextData();
            }
        }, 1000);
    }

    /**
     * 还原单词与选项的颜色
     */
    private void setTextColor() {
        //还原单词选项的颜色
        radioGroup.setEnabled(true);
        radioOne.setEnabled(true);
        radioThree.setEnabled(true);
        radioTwo.setEnabled(true);
        radioFour.setEnabled(true);

        radioOne.setBackgroundColor(Color.parseColor("#ffffff"));      //将选项的按钮设置为白色
        radioTwo.setBackgroundColor(Color.parseColor("#ffffff"));     //将选项的按钮设置为白色
        radioThree.setBackgroundColor(Color.parseColor("#ffffff"));     //将选项的按钮设置为白色
        radioFour.setBackgroundColor(Color.parseColor("#ffffff"));        //将选项的按钮设置为白色
    }
    @SuppressLint("SetTextI18n")
    private void setword(Word word) {
        word_text.setText(word.getHeadWord());
        ukphone_text.setText(word.getUkphone());
        usphone_text.setText(word.getUsphone());
        sentence_text.setText(Sentence_split.getspit(word.getSentences()));
        tranEN_text.setText(word.getTranEN());

        //设置单词收藏状态
        likeButton.setLiked(wordRecordDao.isFlag(word));
        Random random = new Random();
        List<Word> worrywords = new ArrayList<Word>();
        //随机获得三个其他错误单词
        worrywords = wordDao.getwrongwords(3);
        int r = random.nextInt(4);//获取正确答案的选项位置
        switch (r) {
            case 0:
                radioOne.setText("A: " + Tran_CN_split.getspit(word.getTranCN()));
                radioTwo.setText("B: " + Tran_CN_split.getspit(worrywords.get(0).getTranCN()));
                radioThree.setText("C: " + Tran_CN_split.getspit(worrywords.get(1).getTranCN()));
                radioFour.setText("D: " + Tran_CN_split.getspit(worrywords.get(2).getTranCN()));
                break;
            case 1:
                radioOne.setText("A: " + Tran_CN_split.getspit(worrywords.get(0).getTranCN()));
                radioTwo.setText("B: " + Tran_CN_split.getspit(word.getTranCN()));
                radioThree.setText("C: " + Tran_CN_split.getspit(worrywords.get(1).getTranCN()));
                radioFour.setText("D: " + Tran_CN_split.getspit(worrywords.get(2).getTranCN()));
                break;
            case 2:
                radioOne.setText("A: " + Tran_CN_split.getspit(worrywords.get(1).getTranCN()));
                radioTwo.setText("B: " + Tran_CN_split.getspit(worrywords.get(0).getTranCN()));
                radioThree.setText("C: " + Tran_CN_split.getspit(word.getTranCN()));
                radioFour.setText("D: " + Tran_CN_split.getspit(worrywords.get(2).getTranCN()));
                break;
            case 3:
                radioOne.setText("A: " + Tran_CN_split.getspit(worrywords.get(2).getTranCN()));
                radioTwo.setText("B: " + Tran_CN_split.getspit(worrywords.get(0).getTranCN()));
                radioThree.setText("C: " + Tran_CN_split.getspit(worrywords.get(1).getTranCN()));
                radioFour.setText("D: " + Tran_CN_split.getspit(word.getTranCN()));
                break;
        }
        audioMediaPlayer.updateMP(nowword.getHeadWord(), 0);
    }
    @Override
    public void onClick(View v) {
        //播放单词语音
        switch (v.getId()) {
            case R.id.play_vioce_uk://播放单词声音
                audioMediaPlayer.updateMP(nowword.getHeadWord(), 0);
                break;
            case R.id.play_vioce_us:
                audioMediaPlayer.updateMP(nowword.getHeadWord(), 1);
                break;
            case R.id.sentence_text:
                audioMediaPlayer.updateMP(Sentence_split.getspit(nowword.getSentences()), 0);
                break;
            case R.id.tranEN_text:
                audioMediaPlayer.updateMP(nowword.getTranEN(), 0);
                break;
        }
    }

    //点击选项
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        radioGroup.setClickable(false);            //默认选项未被选中

        radioGroup.setEnabled(false);
        radioTwo.setEnabled(false);
        radioOne.setEnabled(false);
        radioThree.setEnabled(false);
        radioFour.setEnabled(false);
        switch (checkedId) {                        //选项的点击事件
            case R.id.choose_btn_one:                //点击“A”选项
                String msg = radioOne.getText().toString().substring(3);        //截取字符串
                btnGetText(msg, radioOne);            //将参数传入到对应的方法里
                break;
            case R.id.choose_btn_two:                //点击“B”选项
                String msg1 = radioTwo.getText().toString().substring(3);    //截取字符串
                btnGetText(msg1, radioTwo);        //将参数传入到对应的方法里
                break;
            case R.id.choose_btn_three:            //点击“C”选项
                String msg2 = radioThree.getText().toString().substring(3);    //截取字符串
                btnGetText(msg2, radioThree);        //将参数传入到对应的方法里
                break;
            case R.id.choose_btn_four:            //点击“D”选项
                String msg3 = radioFour.getText().toString().substring(3);    //截取字符串
                btnGetText(msg3, radioFour);        //将参数传入到对应的方法里
                break;
        }
    }
    private void getNextData() {

        if (CurCount.size() > 0) {
            do {
                now_pos = (now_pos + 1) % needstudy.size();
                nowword = needstudy.get(now_pos);
            } while(!CurCount.containsKey(nowword));
            setTextColor();
            setword(nowword);
        }
        else
        {
            int overTime = timeChangedReceiver.getOpenTime();
            @SuppressLint("DefaultLocale") AlertDialog alertDialog1 = new AlertDialog.Builder(this)
                    .setTitle("恭喜你复习完了!!!!")//标题
                    .setMessage(String.format("本次共复习 % d 分钟 % d个单词!",overTime, needstudy.size()))//内容
                    .setIcon(R.drawable.ic___)//图标
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            finish();
                        }
                    }).
                    setCancelable(false)
                    .create();
            alertDialog1.show();
        }
    }
    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }
    @Override
    protected void onStop() {
        super.onStop();

        unregisterReceiver(timeChangedReceiver);
    }
}